import {ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ActionSheetController, AlertController, LoadingController, ModalController} from '@ionic/angular';
import {NativeService, spinnerList} from '../../services/native.service';
import { PreviewPictureComponent } from '../preview-picture/preview-picture.component';
import { WebView } from "@ionic-native/ionic-webview/ngx";
import { DomSanitizer } from "@angular/platform-browser";
import {Files} from "../../../models/files";
import {QiniuService} from "../../services/qiniu.service";
import {File} from "@ionic-native/file/ngx";
import { Camera } from '@ionic-native/camera/ngx';
import {API} from "../../services/API";
import {HttpService} from "../../services/http/http.service";
import {UUID} from "angular2-uuid";
import {UserInfo} from "../../../models/UserInfo";
import {StorageKey} from "../../Constants";
import {StorageService} from "../../services/storage.service";
declare var MediaPicker: any;

@Component({
    selector: 'app-select-picture',
    templateUrl: './select-picture.component.html',
    styleUrls: ['./select-picture.component.scss'],
})
export class SelectPictureComponent implements OnInit {

    @Input() max = 9;  // 最多可选择多少张图片，默认为9张

    @Input() destinationType = 1;  // 期望返回的图片格式，默认1图片路径，0为返回图片base64

    @Input() allowAdd = true;  // 是否允许新增

    @Input() allowDelete = true;  // 是否允许删除

    @Input() fileObjList = [];  // 图片列表，与fileObjListChange形成双向数据绑定
    @Output() fileObjListChange = new EventEmitter<any>();
    videoUrl: any;
    mediaType: string;
    imgHeight: number;
    img = [];
    path: string;
    paths = [];
    // 图片格式和视频格式
    imgReg = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
    @Input() category1 = '';
    @Input() pictureUrl = '';
    @Input () category2 = '';
    @Input() category3 = '';
    @Input() summaryId = '';
    @Input() applyId = '';
    uuid;
    imgIds = [];
    primaryNo;
    uploadUser;
    imgList = [];
    constructor(public modalCtrl: ModalController,
                private actionSheetCtrl: ActionSheetController,
                private alertCtrl: AlertController,
                private nativeService: NativeService,
                public cd: ChangeDetectorRef,
                private sanitizer: DomSanitizer,
                private webview: WebView,
                private camera: Camera,
                private qiniuService: QiniuService,
                private file: File,
                private httpService: HttpService,
                private storage : StorageService,
                private loadingController: LoadingController,
    ) {
        this.imgHeight = 10;
    }

    async ngOnInit() {
        console.log(this.fileObjList);
        let userInfo: UserInfo = await this.storage.read(StorageKey.PERSON_INFO);
        userInfo = userInfo? userInfo: {};
        this.uploadUser = userInfo.userId;
    }

    async addPicture() {
        const actionSheet = await this.actionSheetCtrl.create({
            buttons: [
                {
                    text: '从相册选择图片',
                    icon: 'images',
                    handler: () => {
                        this.actionSheetCtrl.dismiss().then(() => {
                            this.choosePic();
                        }, () => {
                            this.choosePic();
                        });
                    }
                },
                {
                    text: '拍照',
                    icon: 'camera',
                    handler: () => {
                        this.actionSheetCtrl.dismiss().then(() => {
                            this.takePic();
                        }, () => {
                            this.takePic();
                        });
                    }
                },
                {
                    text: '取消',
                    cssClass: 'quxiao',
                }
            ]
        });
        return await actionSheet.present();
    }

    async viewerPicture(index, event) {
        event.stopPropagation(); // 终止事件冒泡
        const photos = [];
        console.log(this.fileObjList);

        this.fileObjList.forEach((item) => {
            photos.push(item.thumbPath);
        });
        console.log(photos);
        const modal = await this.modalCtrl.create({
            component: PreviewPictureComponent,
            componentProps: {
                images: photos,
                initialIndex: index
            },
        });
        await modal.present();
    }

    async deletePicture(fileObj,index) { // 删除照片
        console.log(this.allowDelete);
        console.log(fileObj);
        console.log(index);
        return await this.nativeService.showConfirm('确认删除吗？', '确定', async () => {
            // @ts-ignore
            console.log(fileObj.id);
            if (fileObj.id){
                const param = {
                    summaryId: this.summaryId,
                    applyId: this.applyId,
                    imgIds: [fileObj.id],
                };
                const info = await this.httpService.post(API.APPLY_IMAGE_DELETE, param, false);
                console.log('157'+info);
                if (info) {
                    this.fileObjList.splice(index, 1);
                    this.fileObjListChange.emit(this.fileObjList);
                    if (!this.fileObjList){
                        this.fileObjList = [];
                    }
                }
            } else {
                this.fileObjList.splice(index, 1);
            }
            this.cd.detectChanges();
        }, '取消');
    }

    private choosePic() {
        const mode = 100;
        this.imgList = [];
        const options = {
            selectMode: mode,
            maxSelectCount: 9,
            maxSelectSize: 200000000,
        };
        MediaPicker.getMedias(options, async (medias) => {
            if (medias.length > 0) {
                for (let i = 0; i < medias.length; i++) {
                    console.log(medias[i]);
                    medias[i].quality = 80;
                    // 如果是视频就不压缩，- -因为这个插件压缩视频会报错：'int android.graphics.Bitmap.getWidth()' on a null object reference
                    if (medias[i].mediaType === 'video') {
                        this.readBuffer(medias[i].uri, medias[i].mediaType);
                        return;
                    }
                    MediaPicker.compressImage(medias[i], (compressData) => {
                        console.log('选择的图片的uri----' + compressData.uri);
                        this.readBuffer(compressData.uri, medias[i].mediaType);
                    }, e => {
                        console.log('Can not compressImage: ' + JSON.stringify(e));
                    });
                }
            }
        }, (e) => {
            console.log('Can not getMedias: ' + JSON.stringify(e));
        });
    }
    private readBuffer(fileUrl, mime) {
        this.mediaType = mime;
        if (this.imgReg.test(fileUrl)) {
            // 解析本地文件系统URL
            this.file.resolveLocalFilesystemUrl(fileUrl)
                .then((entry) => {
                    console.log('Entry: ' + JSON.stringify(entry));
                    this.videoUrl = entry.nativeURL;
                    this.cd.detectChanges();
                    // 查找包含该条目的父DirectoryEntry。如果此条目是其文件系统的根，则其父是它本身。
                    entry.getParent((directoryEntry) => {
                        console.log('Directory entry: ' + JSON.stringify(directoryEntry));
                        // 开始读取文件
                        const data = this.file.readAsArrayBuffer(directoryEntry.nativeURL, entry.name);
                        console.log('data' + JSON.stringify(data));
                        this.file.readAsArrayBuffer(directoryEntry.nativeURL, entry.name)
                            .then(async (imageData: ArrayBuffer) => {
                                // 获取文件后缀和当前时间戳
                                const ind = entry.name.lastIndexOf('.');
                                const fileType = entry.name.substr(ind + 1);
                                const time = new Date().getTime();

                                let blobData: any = {};
                                blobData = new Blob([imageData]);
                                blobData.lastModifiedDate = new Date();
                                blobData.name = `${time}.${fileType}`;
                                const fileObj = {
                                    file: blobData,
                                    origPath: entry.nativeURL,
                                    thumbPath: this.sanitizer.bypassSecurityTrustUrl(
                                        this.webview.convertFileSrc(entry.nativeURL)),
                                    type: mime,
                                    name: blobData.name,
                                    origName: entry.name,
                                } as Files;
                                this.fileObjList.push(fileObj);
                                this.imgList.push(fileObj);
                                let imageFiles = [];
                                console.log(248,this.fileObjList);
                                console.log(252,this.imgList);
                                for (let item of this.imgList){
                                    const data = await this.qiniuService.upload(item.file);
                                    if (data) {
                                        imageFiles.push({
                                            category1: this.category1,
                                            category2: this.category2,
                                            category3: this.category3,
                                            summaryId: this.summaryId,
                                            applyId: this.applyId,
                                            // @ts-ignore
                                            fileName: data.key,
                                            filePath: 'http://loan.i2soft.net',
                                            primaryNo: null,
                                            uploadUser: this.uploadUser,
                                        })
                                    }
                                }
                                console.log(267, imageFiles);
                                const param = {
                                    imageFiles,
                                }
                                const info = await this.httpService.post(API.APPLY_IMAGE_UPLOADS, param, false);
                                console.log('291'+JSON.stringify(info));
                                this.primaryNo = info.primaryNo;
                                this.fileObjListChange.emit(this.fileObjList);
                                this.cd.detectChanges();
                            })}, (error) => {
                        console.log('Can not resolve file directory: ' + JSON.stringify(error));
                    });
                })
                .catch((error) => {
                    console.log('Can not resolve file path: ' + JSON.stringify(error));
                });
        } else {
            this.nativeService.showToast({duration: 2000, message: '暂不支持该格式上传'});
        }
    }

    private takePic() {
        const that = this;
        this.imgList = [];
        const cameraOptions = {quality: 100, mediaType: 0};
        MediaPicker.takePhoto((media) => {
            media.quality = 80;
            MediaPicker.compressImage(media, (compressData) => {
                console.log('拍照的图片的path----' + compressData.uri);
                this.readBuffer(compressData.uri, media.mediaType);
            }, e => {
                console.log('Can not compressImage: ' + JSON.stringify(e));
            });
        }, (e) => {
            console.log('Can not takePhoto: ' + JSON.stringify(e));
        }, cameraOptions);
    }

}

